package com.itheima.health.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author: larry
 * @date: Created in 2020/1/3
 * @description:
 * @version: 1.0
 */
public class DateUtils {
    /**
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param format    转换格式
     * @return
     * @throws Exception
     */
    public static List<String> getMonthBetween(String startDate, String endDate, String format) throws Exception {
        ArrayList<String> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        //由于前端传递的数据最小和最大月份都小1,所以这里再操作的时候需要将最小月份+1,最大加2最后的结果才会正常.
        min.setTime(sdf.parse(startDate));
        min.add(min.get(Calendar.MONTH), 1);
//        System.out.println("+1以后的最小月份变成了:"+min);
        max.setTime(sdf.parse(endDate));
        max.add(max.get(Calendar.MONTH), 2);
//        System.out.println("+2以后的最大月份变成了:"+max);
        SimpleDateFormat sdf2 = new SimpleDateFormat(format);

        Calendar curr = min;
        while (curr.before(max)) {
            curr.add(Calendar.MONTH, 1);
            result.add(sdf2.format(curr.getTime()));
        }
//        System.out.println(result);
        return result;
    }
}